package ru.btabank.dom.util;

import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class DOMUtil {

    public static Node getParentNode(Node node) {
        if (node.getNodeType() == Node.ATTRIBUTE_NODE)
            return ((Attr)node).getOwnerElement();
        else
            return node.getParentNode();
    }

    public static Document getOwnerDocument(Node node) {
        if (node.getNodeType() == Node.DOCUMENT_NODE)
            return (Document)node;
        else
            return node.getOwnerDocument();
    }

    public static Node createElement(Node node, String elementName, String namespaceURI) {
        Document document = getOwnerDocument(node);
        Element newElement = document.createElementNS(namespaceURI, elementName);
        node.appendChild(newElement);
        return newElement;
    }

    public static Node createAttribute(Node node, String attributeName, String namespaceURI) {
        Document document = getOwnerDocument(node);
        Element element = (Element)node;
        Attr newAttribute = document.createAttributeNS(namespaceURI, attributeName);
        element.setAttributeNode(newAttribute);
        return newAttribute;
    }

    public static Node createText(Node node) {
        Document document = getOwnerDocument(node);
        Text text = document.createTextNode("");
        node.appendChild(text);
        return text;
    }

    public static Node createComment(Node node) {
        Document document = getOwnerDocument(node);
        Comment comment = document.createComment("");
        node.appendChild(comment);
        return comment;
    }

    public static String getTextNodesValue(Node node) {
        switch (node.getNodeType()) {
        case Node.DOCUMENT_NODE:
        case Node.ELEMENT_NODE:
            StringBuffer buffer = new StringBuffer();
            NodeList nodes = node.getChildNodes();
            for (int index = 0; index < nodes.getLength(); index++) {
                buffer.append(getTextNodesValue(nodes.item(index)));
            }
            return buffer.toString();
        case Node.TEXT_NODE:
        case Node.CDATA_SECTION_NODE:
            if (node.getNodeValue().trim().length() == 0)
                return "";
            else
                return node.getNodeValue();
        }
        return "";
    }
}
